<template>
  <div id="cart" v-cloak>
    <div class="title">购物车商品总数：{{ count }} 本</div>
    <template v-if="itemlis.length">
      <el-table
        ref="multipleTable"
        :data="itemlis"
        @selection-change="handleSelectionChange"
        stripe
      >
        <el-table-column
          type="selection"
          width="55"
        ></el-table-column>
        <el-table-column prop="bookname" label="商品名称"></el-table-column>
        <el-table-column prop="image" label="封面图" align="center">
          <template slot-scope="scope">
            <router-link :to="'/details/' + scope.row.book_id">
              <img
                :src="api + scope.row.bookimage"
                min-width="80"
                height="80"
              />
            </router-link>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="商品单价"></el-table-column>
        <el-table-column align="right" width="50">
          <template slot-scope="scope">
            <span
              style="color:red;font-size:16px;cursor: pointer;"
              @click.prevent="delRow(scope.row, scope.$index)"
              ><i class="el-icon-minus"></i
            ></span>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" min-width="25">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.number"
              oninput="value=value.replace(/[^\d]/g,'')"
              maxlength="8"
              readonly="readonly"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column align="left" width="50">
          <template slot-scope="scope">
            <span
              style="color:#409EFF;font-size:16px;cursor: pointer;"
              @click.prevent="addRow(scope.row, scope.$index)"
              ><i class="el-icon-plus"></i
            ></span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="小计">
          <template slot-scope="scope">
            ¥{{ (scope.row.sum = scope.row.price * scope.row.number) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="total">
        <p>*本系统只支持单次只能购买单个商品</p>
        <div class="freight">
          <div class="item">运费：{{ freight }}</div>
        </div>
        <div class="freight">
          <div class="item">订单总计: ¥{{ totalPrice }}</div>
        </div>
        <div class="freight">
          <input
            type="button"
            v-show="isgotocheckstand"
            value="前往收银台"
            @click="gotocheckstand()"
          />
        </div>
      </div>
    </template>
    <div class="carnull" v-else>
      <span>购物车空空如也...</span>
      <el-button type="primary" plain @click="gotocategory">去购物</el-button>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      itemlis: [],
      freight: "免费配送",
      api: this.imageapi,
      id: sessionStorage.getItem("id"),
      multipleSelection: [],
      isgotocheckstand: true
    };
  },
  computed: {
    //计算并获取总价
    totalPrice() {
      let total = 0;
      for (let i = 0; i < this.multipleSelection.length; i++) {
        let item = this.multipleSelection[i];
        total += item.price * item.number;
      }
      return total.toString().replace(/\B(?=(\d{3})+$)/g, ",");
    },
    count() {
      let count = 0;
      for (let i = 0; i < this.itemlis.length; i++) {
        let item = this.itemlis[i];
        count += item.number;
      }
      return count.toString().replace(/\B(?=(\d{3})+$)/g, ",");
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    // 获取购物车列表
    init() {
      const that = this;
      let id = that.id;
      that.$http.post("/showshopcart", { id }).then(res => {
        // console.log(res);
        that.itemlis = res.data;
        // that.$store.commit("addCar", res.data);
      });
    },
    // //增加商品数量
    addRow(row) {
      row.number = row.number + 1;
      let count = row.number;
      let id = row.id;
      const that = this;
      that.$http.post("/addshopcartnumber", { id, count });
      // that.$router.go(0)
      // that.init();
    },
    //减少商品数量
    delRow(row) {
      if (row.number != 1) {
        row.number = row.number - 1;
        let count = row.number;
        let id = row.id;
        const that = this;
        that.$http.post("/downshopcartnumber", { id, count });
        // that.$router.go(0)
        // that.init();
      }
    },
    //从购物车中移除该商品
    handleDelete(id) {
      const that = this;
      that
        .$confirm("此操作删除购物车数据不可恢复, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true
        })
        .then(() => {
          that.$http.post("/deleteshopcart", { id }),
            that.$message({
              type: "success",
              message: "删除成功!"
            });
          for (let i in that.itemlis) {
            if (that.itemlis[i].id == id) {
              that.itemlis.splice(i, 1); //删除不请求数据，直接在数组中删除
              break;
            }
          }
        })
        .catch(() => {
          that.$message({
            type: "info",
            message: "已取消删除"
          });
        });
      // for (let i in this.itemlis) {
      //   if (this.itemlis[i].id == id) {
      //     this.itemlis.splice(i, 1); //删除不请求数据，直接在数组中删除
      //     break;
      //   }
      // }
    },
    // 购物车为空 点击跳转到分类页
    gotocategory() {
      this.$router.push({ name: "category" });
    },
    // 点击跳转收银台页面
    gotocheckstand() {
      if ((this.multipleSelection.length == 0)) {
        this.$message({
          message: "请先选择商品...",
          type: "warning"
        });
      } else {
        this.$router.push({
          path: "/checkstand",
          query: { data: JSON.stringify(this.multipleSelection)}
        });
      }
    },
    // 选择商品
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(val);
    }
  }
};
</script>

<style scoped>
#cart {
  width: 1200px;
  margin: 20px auto;
}
.title {
  border-bottom: 3px solid #dcdada;
  margin: 10px;
  padding-bottom: 10px;
  font-size: 16;
  font-weight: bold;
  color: #777;
}

.carnull {
  width: 100%;
  margin: 100px auto;
}
.carnull span {
  display: block;
  margin: 50px auto;
  text-align: center;
}
.el-button {
  display: block;
  margin: 0 auto;
}
.total {
  border-top: 3px solid #dcdada;
  margin: 30px auto;
}
.total p{
  font-size: 16px;
  color: #999;
}
.freight {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  padding: 10px;
  font-size: 15px;
  color: #514f4f;
}
.freight .item {
  width: 150px;
  border-bottom: 2px solid #eee;
  padding-bottom: 3px;
}
input {
  font-size: 16px;
  color: #ffffff;
  border-color: #337dff;
  background-color: #337dff;
  padding: 8px 32px;
  outline: none;
  cursor: pointer;
}
</style>
